package com.linln.admin.app.controller;

import com.linln.admin.app.domain.AppInfo;
import com.linln.admin.app.service.InfoService;
import com.linln.admin.app.service.ProductionLineService;
import com.linln.admin.app.service.RepoAccountService;
import com.linln.admin.app.validator.InfoValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.actionLog.action.SaveAction;
import com.linln.component.actionLog.action.StatusAction;
import com.linln.component.actionLog.annotation.ActionLog;
import com.linln.component.actionLog.annotation.EntityParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 陶富成
 * @date 2021/07/08
 */
@Slf4j
@Controller
@RequestMapping("/app/info")
public class InfoController {

    @Autowired
    private InfoService infoService;
    @Autowired
    private RepoAccountService accountService;
    @Autowired
    private ProductionLineService productionLineService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("app:info:index")
    public String index(Model model, AppInfo appInfo) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("display_name", match -> match.contains())
                .withMatcher("repo_url", match -> match.contains());

        // 获取数据列表
        Example<AppInfo> example = Example.of(appInfo, matcher);
        Page<AppInfo> list = infoService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        initList(model);
        return "/app/info/index";
    }

    private void initList(Model model) {
        model.addAttribute("accounts", accountService.getAll());
        model.addAttribute("prodLines", productionLineService.getAll());
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("app:info:add")
    public String toAdd(Model model) {
        initList(model);
        return "/app/info/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("app:info:edit")
    public String toEdit(@PathVariable("id") AppInfo appInfo, Model model) {
        model.addAttribute("appInfo", appInfo);
        initList(model);
        return "/app/info/add";
    }

    /**
     * 保存添加/修改的数据
     *
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"app:info:add", "app:info:edit"})
    @ResponseBody
    @ActionLog(name = "应用信息管理", message = "应用：${display_name}", action = SaveAction.class)
    public ResultVo save(@Validated InfoValid valid, @EntityParam AppInfo appInfo) {
        // 复制保留无需修改的数据
        if (appInfo.getId() != null) {
            AppInfo beAppInfo = infoService.getById(appInfo.getId());
            EntityBeanUtil.copyProperties(beAppInfo, appInfo);
        }

        // 保存数据
        infoService.save(appInfo);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("app:info:detail")
    public String toDetail(@PathVariable("id") AppInfo appInfo, Model model) {
        model.addAttribute("appInfo", appInfo);
        initList(model);
        return "/app/info/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("app:info:status")
    @ResponseBody
    @ActionLog(name = "应用状态", action = StatusAction.class)
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (infoService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }

    //git上的分支管理

    /**
     * 获取所有分支名称
     *
     * @param appId
     * @param model
     * @return
     */
    @GetMapping("/branch/list")
    @RequiresPermissions("app:info:branch:list")
    public String appBranchList(Long appId, Model model) {
        model.addAttribute("appId", appId);
        model.addAttribute("apps", infoService.getAll());
        return "/app/info/branch_list";
    }

    @PostMapping("/branch/checkboxs")
    @RequiresPermissions("app:info:branch:list")
    public String getBranchChechboxs(Long appId, Model model) {
        model.addAttribute("branchs", infoService.fetchAllGitBranchsByAppId(appId));
        return "/app/info/branch_checkboxs";
    }

    /**
     * 删除指定分支
     *
     * @param appId
     * @param branchs
     * @return
     */
    @PostMapping("/branch/delete")
    @RequiresPermissions({"app:info:branch:delete"})
    @ResponseBody
    @ActionLog(name = "应用分支清理", message = "清理应用分支:appId=${appId},branches=${branchs}")
    public ResultVo deleteBranchs(Long appId, String[] branchs) {
        // 将选中的分支删除掉
        try {
            infoService.deleteGitBranchsByAppId(appId, branchs);
            return ResultVoUtil.SAVE_SUCCESS;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultVoUtil.error(e.getMessage());
        }
    }
}